<script lang="ts" setup>
import { ElButton, ElInput, Sort } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { Table } from '@/components/Table'
import { getOpenUsersListApi, delOpenUsersListApi } from '@/api/open-user'
import { useTable } from '@/hooks/web/useTable'
import { reactive, ref } from 'vue'
import { useRouter } from 'vue-router'
import { TableColumn } from '@/types/table'
import { Search, SearchItem } from '@/components/Search'
import { OpenUser } from '@/api/open-user/types'

defineOptions({
  name: 'OpenUser'
})

const { push } = useRouter()

const conditions = reactive({
  nickname: '',
  openid: ''
})

const defaultSort = ref<Sort>({
  prop: 'created_at',
  order: 'descending'
})

const { register, tableObject, methods } = useTable<OpenUser>({
  getListApi: getOpenUsersListApi,
  delListApi: delOpenUsersListApi,
  defaultSort: defaultSort.value
})

const { setSearchParams, onSortChanged } = methods

setSearchParams(conditions)

const tableColumns = reactive<TableColumn[]>([
  {
    field: 'openid',
    label: '小程序id',
    width: '300px'
  },
  {
    field: 'nickname',
    label: '微信昵称',
    width: 'auto',
    showOverflowTooltip: true
  },
  {
    field: 'country',
    label: '国家',
    width: '100px'
  },
  {
    field: 'province',
    label: '省份',
    width: '100px'
  },
  {
    field: 'city',
    label: '城市',
    width: '100px'
  },
  {
    field: 'avatar',
    label: '头像',
    width: '100px'
  }
])

const DownloadAction = () => {
  push('/geography/region-add')
}
</script>

<template>
  <Search :model="conditions" @reset="setSearchParams" @search="setSearchParams">
    <SearchItem label="微信昵称" prop="nickname">
      <ElInput v-model="conditions.nickname" clearable maxlength="50" />
    </SearchItem>
    <SearchItem label="小程序id" prop="openid">
      <ElInput v-model="conditions.openid" clearable maxlength="50" />
    </SearchItem>
  </Search>

  <div class="mt-10px bg-white p-20px">
    <div class="mb-10px flex flex-row justify-between">
      <div>列表</div>
      <div class="flex flex-row items-center">
        <ElButton :icon="Plus" type="primary" @click="DownloadAction">下载</ElButton>
        <Icon class="mr-8px ml-8px cursor-pointer" icon="ep:refresh-right" />
      </div>
    </div>

    <Table
      v-model:currentPage="tableObject.currentPage"
      v-model:pageSize="tableObject.pageSize"
      :columns="tableColumns"
      :data="tableObject.tableList"
      :default-sort="defaultSort"
      :loading="tableObject.loading"
      :pagination="{
        total: tableObject.total
      }"
      :selection="false"
      @register="register"
      @sort-change="onSortChanged"
    />
  </div>
</template>
